String.prototype.endWith = function(str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substring(this.length - str.length) == str)
        return true;
    else
        return false;
    return true;
}

String.prototype.startWith = function(str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}

function getCodes(files, path) {
    path = path || '';
    var origCode = '';
    var fs = require('fs');
    if (files) {
        for (var i = 0; i < files.length; i++) {
            var name = files[i];
            if (name.endWith('/')) {
                var _, _, list = fs.readdirSync(name);
                origCode += getCodes(list, path + name);
            } else {
                console.log('getCodes: ' + path + name);
                origCode += "\n<!-----" + path + name + "----->\n"
                origCode += fs.readFileSync(path + name, 'utf8');
            }
        }
    }
    return origCode;
}

function buildAll(fileIn, filePage, fileOut) {
    var codes = getCodes(fileIn);
    var fs = require('fs');
    var indexPage = getIndexHtmlContent(filePage);
    if (indexPage) {
        codes = indexPage[0] + codes + '\n' + indexPage[1];
    }
    fs.writeFileSync(fileOut, codes, 'utf8');
}

function getIndexHtmlContent(filePage) {
    var fs = require('fs');
    var first = '';
    indexHtml = fs.readFileSync(filePage, 'utf8');
    var bodyStart = '<body class="app">';
    var idx = indexHtml.indexOf(bodyStart);
    if (idx > 0) {
        first = indexHtml.substring(0, idx + bodyStart.length);
        var bodyEnd = '</body>';
        idx = indexHtml.lastIndexOf(bodyEnd);
        var second = indexHtml.substring(idx);
        return [first, second];
    }
    return undefined;
}

buildAll([
    // module
    'htmls/loading.html',
    'htmls/sections/',
    'htmls/scripts.html',
], 'htmls/base.html', 'index.html');

